package cn.school.demo.ui.answer

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentAnswerMainBinding
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog
import java.time.LocalDateTime
import java.time.LocalTime

class AnswerMainFragment : Fragment() {
    private lateinit var viewModel: AnswerViewModel
    private lateinit var binding: FragmentAnswerMainBinding
    private lateinit var count: CountDownTimer

    @SuppressLint("NewApi")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val map = GsonUtils.fromJson<Map<String, String>>(
            arguments?.getString("map"),
            object : TypeToken<Map<String, String>>() {}.type
        )
        viewModel = ViewModelProvider(this).get(AnswerViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_answer_main, container, false)
        binding.vm = viewModel
        binding.vw = this
        binding.my = MyApplication
        binding.lifecycleOwner = viewLifecycleOwner
        if (MyApplication.isNotify) {
            val startTime = MyApplication.notifyList[MyApplication.answerTopic]?.startTime
            val endTime = MyApplication.notifyList[MyApplication.answerTopic]?.endTime
            if (!startTime.isNullOrEmpty() && !endTime.isNullOrEmpty()) {
                val nowTime = LocalDateTime.now()
                if (LocalDateTime.parse(startTime) < nowTime && LocalDateTime.parse(endTime) > nowTime) {
                    viewModel.getSubjectListById().observe(viewLifecycleOwner) {
                        if (it.size == 0 && !MyApplication.isNoFresh) {
                            CircleDialog.Builder().setText("已经作答，请勿重复作答！").setNegative("返回") {
                                MyApplication.goto(
                                    R.id.action_AnswerMain_to_PartyHistoryAnswer,
                                    findNavController(),
                                    parentFragmentManager
                                )
                            }.show(parentFragmentManager)
                        } else {
                            if (!it.isNullOrEmpty()) {
                                MyApplication.apply {
                                    subjectList.clear()
                                    subjectList.addAll(it)
                                    isNotify = false
                                    //pendingIntent = null
                                    viewModel.setSubject(subjectList[0])
                                    LogUtils.d(viewModel.subject.value)
                                    notifyList.remove(answerTopic)
                                }
                                init()
                            } else {
                                CircleDialog.Builder().setText("数据库错误！").setNegative("确定") {
                                    MyApplication.goto(
                                        R.id.action_AnswerMain_to_PartyHistoryAnswer,
                                        findNavController(),
                                        parentFragmentManager
                                    )
                                }
                                    .show(parentFragmentManager)
                            }
                        }
                    }
                } else {
                    CircleDialog.Builder()
                        .setText("请在$startTime-${endTime}内进行作答！").setNegative("确定") {
                            MyApplication.goto(
                                R.id.action_AnswerMain_to_PartyHistoryAnswer,
                                findNavController(),
                                parentFragmentManager
                            )
                        }.show(parentFragmentManager)
                }
            }
        } else {
            init()
        }
        viewModel.setOrigin(map["title"].toString())
        return binding.root
    }

    @SuppressLint("SetTextI18n", "NewApi")
    fun init() {
        MyApplication.answerScore.apply {
            trueNumber = 0
            errorNum = getAllNumber().toInt() - trueNumber
            correctRate = 0f
            useTime = "00:00:00"
            integralNum = 0
        }
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        binding.apply {
            answerMainNextButton.visibility = View.INVISIBLE
            answerMainTestAnswerCard.visibility = View.GONE
            answerMainNextButton.text = "下一题"
            answerMainTestNumber.text =
                (viewModel.number.value!! + 1).toString() + "/" + getAllNumber()
            if (MyApplication.isSubject) {
                fragmentAnswerMainChronometer.apply {
                    visibility = View.VISIBLE
                    count = object : CountDownTimer((3 * 60 * 60 * 1000), 1000) {
                        override fun onTick(p0: Long) {
                            fragmentAnswerMainChronometer.text =
                                "剩余时间: ${LocalTime.ofSecondOfDay(p0 / 1000)}"
                        }

                        override fun onFinish() {
                            CircleDialog.Builder().setText("答题时间结束，试卷自动提交！").setNegative("确定") {
                                viewModel.setEndTime(LocalDateTime.now())
                                MyApplication.answerScore.useTime = viewModel.endTime.toString()
                                viewModel.apply {
                                    val s = saveIntegral()
                                    s.observe(viewLifecycleOwner) {
                                        when (it.success) {
                                            true -> {
                                                MyApplication.apply {
                                                    user!!.totalIntegral += answerScore.trueNumber
                                                }
                                            }
                                            else -> {
                                                CircleDialog.Builder().setText(it.message)
                                                    .setTextColor(Color.RED)
                                                    .setNegative("确定", null)
                                                    .show(parentFragmentManager)
                                            }
                                        }
                                        MyApplication.goto(
                                            R.id.action_AnswerMain_to_answerScore,
                                            findNavController(),
                                            parentFragmentManager
                                        )
                                    }
                                }
                            }.show(parentFragmentManager)
                        }
                    }.start()
                }
            }
        }
        viewModel.test.observe(viewLifecycleOwner) {
            if (!MyApplication.isSubject) {
                upDateTestObserve()
            }
        }
        viewModel.subject.observe(viewLifecycleOwner) {
            if (MyApplication.isSubject) {
                upDateSubjectObserve()
            }
        }
    }

    /*==============更新题目的方法=====================*/
    @SuppressLint("SetTextI18n")
    private fun upDateTestObserve() {
        viewModel.test.value?.let {
            val test = it
            binding.apply {
                answerMainTestText.text = test.question
                answerMainSelectByA.text = " A. " + test.optionOne
                answerMainSelectByB.text = " B. " + test.optionTwo
                answerMainSelectByC.text = " C. " + test.optionThree
                answerMainSelectByD.text = " D. " + test.optionFour
                answerMainTrueAnswer.text = test.answer
                LogUtils.d("Test更新了")
            }
        } ?: CircleDialog.Builder().setText("系统错误，更新题目失败").setTextColor(Color.RED)
            .setNegative("返回党史答题界面") {
                MyApplication.goto(
                    R.id.action_AnswerMain_to_PartyHistoryAnswer,
                    findNavController(),
                    parentFragmentManager
                )
            }.show(parentFragmentManager)
    }

    @SuppressLint("SetTextI18n")
    private fun upDateSubjectObserve() {
        viewModel.subject.value?.let {
            val subject = it
            binding.apply {
                answerMainTestText.text = subject.subjectContent
                answerMainSelectByA.text = " A. " + subject.optionOne
                answerMainSelectByB.text = " B. " + subject.optionTwo
                answerMainSelectByC.text = " C. " + subject.optionThree
                answerMainSelectByD.text = " D. " + subject.optionFour
                answerMainTrueAnswer.text = subject.subjectAnswer
            }
            LogUtils.d("Subject更新了")
        } ?: CircleDialog.Builder().setText("系统错误，更新题目失败").setTextColor(Color.RED)
            .setNegative("返回答题界面") {
                MyApplication.goto(
                    R.id.action_AnswerMain_to_My_Answer,
                    findNavController(),
                    parentFragmentManager
                )
            }.show(parentFragmentManager)
    }
    /*=============================================*/

    //获取题目总数量
    private fun  getAllNumber(): String {
        return if (MyApplication.isSubject)
            MyApplication.subjectList.size.toString()
        else if (!MyApplication.isSubject)
            MyApplication.testList.size.toString()
        else "5"
    }

    //返回按钮监听
    fun gotoBack() {
        CircleDialog.Builder().setText("您正在答题，确定要退出吗？(一旦退出可能无法在此进入！)").setPositive("退出") {
            MyApplication.navigateThing["AnswerMain"]?.let {
                MyApplication.goto(
                    MyApplication.navigateThing["AnswerMain"]!!.toInt(),
                    findNavController(),
                    parentFragmentManager
                )
            } ?: let {
                count.cancel()
                MyApplication.goto(
                    R.id.action_AnswerMain_to_PartyHistoryAnswer,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }.setNegative("继续答题", null).show(parentFragmentManager)
    }

    fun clickTrueButton() {
        binding.apply {
            when (viewModel.chooseButton.value) {
                1 -> if ((viewModel.test.value!!.answer == "A" && !MyApplication.isSubject) ||
                    (viewModel.subject.value!!.subjectAnswer == "A" && MyApplication.isSubject)
                ) {
                    viewModel.setScore(1)
                    answerMainSelectByA.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_true)
                        setTextColor(resources.getColorStateList(R.color.answer_true_text, null))
                    }
                    chanceTrueButtonUIByIsTrue()
                } else {
                    answerMainSelectByA.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_error)
                        setTextColor(resources.getColorStateList(R.color.red, null))
                    }
                    answerMainTestAnswerCard.visibility = View.VISIBLE
                    chanceNextButtonUI()
                }
                2 -> if ((viewModel.test.value!!.answer == "B" && !MyApplication.isSubject) ||
                    (viewModel.subject.value!!.subjectAnswer == "B" && MyApplication.isSubject)
                ) {
                    viewModel.setScore(1)
                    answerMainSelectByB.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_true)
                        setTextColor(resources.getColorStateList(R.color.answer_true_text, null))
                    }
                    chanceTrueButtonUIByIsTrue()
                } else {
                    answerMainSelectByB.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_error)
                        setTextColor(resources.getColorStateList(R.color.red, null))
                    }
                    answerMainTestAnswerCard.visibility = View.VISIBLE
                    chanceNextButtonUI()
                }
                3 -> if ((viewModel.test.value!!.answer == "C" && !MyApplication.isSubject) ||
                    (viewModel.subject.value!!.subjectAnswer == "C" && MyApplication.isSubject)
                ) {
                    viewModel.setScore(1)
                    answerMainSelectByC.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_true)
                        setTextColor(resources.getColorStateList(R.color.answer_true_text, null))
                    }
                    chanceTrueButtonUIByIsTrue()
                } else {
                    answerMainSelectByC.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_error)
                        setTextColor(resources.getColorStateList(R.color.red, null))
                    }
                    answerMainTestAnswerCard.visibility = View.VISIBLE
                    chanceNextButtonUI()
                }
                4 -> if ((viewModel.test.value!!.answer == "D" && !MyApplication.isSubject) ||
                    (viewModel.subject.value!!.subjectAnswer == "D" && MyApplication.isSubject)
                ) {
                    viewModel.setScore(1)
                    answerMainSelectByD.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_true)
                        setTextColor(resources.getColorStateList(R.color.answer_true_text, null))
                    }
                    chanceTrueButtonUIByIsTrue()
                } else {
                    answerMainSelectByD.apply {
                        setBackgroundResource(R.drawable.button_shape_answer_item_error)
                        setTextColor(resources.getColorStateList(R.color.red, null))
                    }
                    answerMainTestAnswerCard.visibility = View.VISIBLE
                    chanceNextButtonUI()
                }
            }
            answerMainTrueButton.visibility = View.GONE
            answerMainSelectByA.isEnabled = false
            answerMainSelectByB.isEnabled = false
            answerMainSelectByC.isEnabled = false
            answerMainSelectByD.isEnabled = false
        }
    }

    @SuppressLint("NewApi", "SetTextI18n")
    fun clickButton() {
        viewModel.plusNumber()
        binding.apply {
            if ((MyApplication.isSubject && viewModel.subject.value == MyApplication.subjectList[MyApplication.subjectList.size - 1]) ||
                !MyApplication.isSubject && viewModel.test.value == MyApplication.testList[MyApplication.testList.size - 1]
            ) {
                viewModel.apply {
                    setEndTime(LocalDateTime.now())
                    val s = saveIntegral()
                    s.observe(viewLifecycleOwner) {
                        when (it.success) {
                            true -> {
                                MyApplication.apply {
                                    user!!.totalIntegral += answerScore.trueNumber*1
                                    goto(
                                        R.id.action_AnswerMain_to_answerScore,
                                        findNavController(),
                                        parentFragmentManager
                                    )
                                }
                            }
                            else -> {
                                CircleDialog.Builder().setText(it.message)
                                    .setTextColor(Color.RED)
                                    .setNegative("确定", null).show(parentFragmentManager)
                            }
                        }
                    }
                }
            } else {
                answerMainTestNumber.text = "${viewModel.number.value!! + 1}/${getAllNumber()}"
                if (MyApplication.isSubject)
                    viewModel.setSubject(MyApplication.subjectList[viewModel.number.value!!])
                else if (!MyApplication.isSubject)
                    viewModel.setTest(MyApplication.testList[viewModel.number.value!!])
                initialUI()
            }
        }
    }

    private fun chanceNextButtonUI() {
        if ((MyApplication.isSubject && viewModel.subject.value == MyApplication.subjectList[MyApplication.subjectList.size - 1]) ||
            !MyApplication.isSubject && viewModel.test.value == MyApplication.testList[MyApplication.testList.size - 1]
        ) {
            binding.answerMainNextButton.apply {
                visibility = View.VISIBLE
                text = "提交"
            }
        } else {
            binding.answerMainNextButton.apply {
                visibility = View.VISIBLE
                text = "下一题"
            }
        }
    }

    //判断显示UI，若最后一题自动触发提交监听
    private fun chanceTrueButtonUIByIsTrue() {
        if ((MyApplication.isSubject && viewModel.subject.value == MyApplication.subjectList[MyApplication.subjectList.size - 1]) ||
            !MyApplication.isSubject && viewModel.test.value == MyApplication.testList[MyApplication.testList.size - 1]
        ) {
            chanceNextButtonUI()
        } else {
            object : CountDownTimer(1000, 1000) {
                override fun onTick(p0: Long) { //什么也不做
                }

                override fun onFinish() {
                    clickButton()
                }
            }.start()
        }
    }

    //记录选择的选项，更新UI
    fun tagOnClick(choose: Int) {
        when (choose) {
            1 -> {
                LogUtils.v("我选择了A选项")
                initialUI()
                binding.answerMainTrueButton.visibility = View.VISIBLE
                binding.answerMainSelectByA.setBackgroundResource(R.drawable.button_shape_answer_item_selected)
                viewModel.setChooseButton(1)
            }
            2 -> {
                LogUtils.v("我选择了B选项")
                initialUI()
                binding.answerMainTrueButton.visibility = View.VISIBLE
                binding.answerMainSelectByB.setBackgroundResource(R.drawable.button_shape_answer_item_selected)
                viewModel.setChooseButton(2)
            }
            3 -> {
                LogUtils.v("我选择了C选项")
                initialUI()
                binding.answerMainTrueButton.visibility = View.VISIBLE
                binding.answerMainSelectByC.setBackgroundResource(R.drawable.button_shape_answer_item_selected)
                viewModel.setChooseButton(3)
            }
            4 -> {
                LogUtils.v("我选择了D选项")
                initialUI()
                binding.answerMainTrueButton.visibility = View.VISIBLE
                binding.answerMainSelectByD.setBackgroundResource(R.drawable.button_shape_answer_item_selected)
                viewModel.setChooseButton(4)
            }
        }
    }

    //界面UI恢复最初的状态
    private fun initialUI() {
        binding.apply {
            answerMainTestAnswerCard.visibility = View.GONE
            answerMainNextButton.visibility = View.INVISIBLE
            answerMainSelectByA.apply {
                isEnabled = true
                setBackgroundResource(R.drawable.button_shape_answer_item_unselected)
                setTextColor(resources.getColorStateList(R.color.black, null))
            }
            answerMainSelectByB.apply {
                isEnabled = true
                setBackgroundResource(R.drawable.button_shape_answer_item_unselected)
                setTextColor(resources.getColorStateList(R.color.black, null))
            }
            answerMainSelectByC.apply {
                isEnabled = true
                setBackgroundResource(R.drawable.button_shape_answer_item_unselected)
                setTextColor(resources.getColorStateList(R.color.black, null))
            }
            answerMainSelectByD.apply {
                isEnabled = true
                setBackgroundResource(R.drawable.button_shape_answer_item_unselected)
                setTextColor(resources.getColorStateList(R.color.black, null))
            }
        }
    }

}